﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using Yipusoft.Common.BLL;
using Yipusoft.Common.Model;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Yipusoft.TownshipEnterprise.BLL;
using Yipusoft.TownshipEnterprise.Model;

public partial class TownshipEnterprise_DeviceList : System.Web.UI.Page
{

    //设置每页行数
    private int pageSize = 20;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["cap"] != null)
            {
                UserGrid.Caption = Request.QueryString["cap"].ToString() + "装备器材列表";
            }
            if (!Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200500") && !Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200509") && !Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200510") && !Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200503"))
            {
                Response.Write("<script>alert('没有权限！');history.back(0);</script>");
                return;
            }
            //部门
            UserInfo userInfo = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
            DepartmentInfo department = Department.GetDepartment(userInfo.DepartmentID);
            if (userInfo.DepartmentID.Substring(0, 4) == "1300")
            {
                DepartmentList.DataSource = Yipusoft.Account.BLL.Department.GetList(" (SUBSTRING(DepartmentID, 5, 3) = '000') and DepartmentID<>'1300000' ");
                DepartmentList.DataBind();
                DepartmentListBind();
            }
            else
            {
                DepartmentList.DataSource = Yipusoft.Account.BLL.Department.GetList(" DepartmentID= '" + department.DepartmentID.Substring(0, 4) + "000' ");
                DepartmentList.DataBind();
                DepartmentListBind();
            }

            if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200510"))
            {
                DepartmentList.SelectedValue = department.DepartmentID.Substring(0, 4) + "000";
                //DepartmentList.Enabled = false;
                DepartmentListBind();
            }
            else

                if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200503"))
                {
                    DepartmentList.SelectedValue = department.DepartmentID.Substring(0, 4) + "000";
                    //DepartmentList.Enabled = false;
                    DepartmentListBind();
                    UnitList.SelectedValue = department.DepartmentID;
                    //UnitList.Enabled = false;
                }


            //BindCodeItemList(DeviceClassList, "ZBQC010000");
            BindType();
            BindClass();
            ButtonDelete.Attributes.Add("onclick", "return confirm('确定删除所选记录吗？');");
            BindGrid(0);
        }
    }

    void DepartmentListBind()
    {
        //if (DepartmentList.SelectedValue == "")
        //{
        //    UnitList.Items.Clear();
        //    UnitList.Items.Add(new ListItem("------------部门-------------", ""));
        //    UnitList.DataSource = null;
        //    UnitList.DataBind();
        //}
        //else
        //{
        //    UnitList.Items.Clear();
        //    UnitList.Items.Add(new ListItem("------------部门-------------", ""));
        //    string strWhere = "(departmentid like '" + DepartmentList.SelectedValue.Substring(0, 4) + "2%'  and  SUBSTRING(DepartmentID, 5, 1)<>'0') or departmentid='" + DepartmentList.SelectedValue + "'";
        //    UnitList.DataSource = Department.GetList(strWhere);
        //    UnitList.DataBind();
        //}
        UnitList.Items.Clear();
        UnitList.Items.Add(new ListItem("------------部门-------------", ""));
        if (DepartmentList.Items.Count <= 0)
            return;
        if (DepartmentList.SelectedValue.ToString() == "")
            return;

        //UnitList.Items.Clear();
        string strWhere = "DepartmentID like '" + DepartmentList.SelectedValue.Substring(0, 4) + "2%' and   SUBSTRING(DepartmentID, 5, 1)<>'0' and shortname like'%大队'";
        List<DepartmentInfo> list = Department.GetList(strWhere);
        foreach (DepartmentInfo dpt in list)
        {
            dpt.ShortName = dpt.ShortName.Replace("大队", "");
            dpt.ShortName = dpt.ShortName.Replace("消防", "");
        }
        UnitList.DataSource = list;
        UnitList.DataBind();
    }

    private void BindCodeItemList(DropDownList ddl, string parentID)
    {
        ListItem li;
        List<CodeItemInfo> items = CodeItem.GetList("ParentID='" + parentID + "' ORDER BY SeqID");
        foreach (CodeItemInfo item in items)
        {
            li = new ListItem();
            li.Text = "".PadRight(2 * (item.ItemLevel - 1), '　') + item.ItemName;
            li.Value = item.ItemID;
            ddl.Items.Add(li);
            BindCodeItemList(ddl, item.ItemID);
        }
    }
    protected void DeviceClassList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindGrid(0);
    }
    protected void ButtonAttachment_Click(object sender, EventArgs e)
    {
        if (!Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200500") && !Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200505"))
        {
            Response.Write("<script>alert('没有权限！');history.back(0);</script>");
            return;
        }
        for (int i = 0; i < UserGrid.Rows.Count; i++)
        {
            CheckBox cb = (CheckBox)UserGrid.Rows[i].FindControl("CheckItem");
            if (cb.Checked)
            {
                if (!IsClientScriptBlockRegistered("OpenScript"))
                {
                    RegisterStartupScript("OpenScript", "<script>OpenWin('../Common/Upload.aspx?ItemID=" + UserGrid.DataKeys[i].Values[0].ToString() + "');</script>");
                }
                //Response.Redirect("../../Common/Upload.aspx?ItemID=" + UserGrid.DataKeys[i].Values[0].ToString());
            }
        }
        Prompt.Text = "警告：请选择记录";
    }
    protected void ButtonLog_Click(object sender, EventArgs e)
    {
        if (!Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200500") && !Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200506"))
        {
            Response.Write("<script>alert('没有权限！');history.back(0);</script>");
            return;
        }
        for (int i = 0; i < UserGrid.Rows.Count; i++)
        {
            CheckBox cb = (CheckBox)UserGrid.Rows[i].FindControl("CheckItem");
            if (cb.Checked)
            {
                if (!IsClientScriptBlockRegistered("OpenScript"))
                {
                    RegisterStartupScript("OpenScript", "<script>OpenWin('../Common/LogList.aspx?ItemID=" + UserGrid.DataKeys[i].Values[0].ToString() + "');</script>");
                }
                //Response.Redirect("../../Common/LogList.aspx?ItemID=" + UserGrid.DataKeys[i].Values[0].ToString());
            }
        }
        Prompt.Text = "警告：请选择记录";
    }
    public string GetCodeItem(string deviceClass)
    {
        Yipusoft.Common.Model.CodeItemInfo info = CodeItem.GetCodeItem(deviceClass);
        return info != null ? info.ItemName : "";
    }

    #region 通用代码
    protected void ButtonEdit_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < UserGrid.Rows.Count; i++)
        {
            CheckBox cb = (CheckBox)UserGrid.Rows[i].FindControl("CheckItem");
            if (cb.Checked)
            {
                Response.Redirect("DeviceAdd.aspx?DeviceID=" + UserGrid.DataKeys[i].Values[0].ToString());
                break;
            }
        }
        Prompt.Text = "警告：请选择记录";
    }
    protected void ButtonDelete_Click(object sender, EventArgs e)
    {
        if (!Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200500") && !Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200504"))
        {
            Response.Write("<script>alert('没有权限！');history.back(0);</script>");
            return;
        }

        int affectedRows = 0;
        for (int i = 0; i < UserGrid.Rows.Count; i++)
        {
            CheckBox cb = (CheckBox)UserGrid.Rows[i].FindControl("CheckItem");
            if (cb.Checked)
            {
                //EventLogInfo log = new EventLogInfo();
                //log.EventTime = DateTime.Now;
                //log.EventType = 1;
                //log.EventData = "删除记录";
                //log.ItemID = UserGrid.DataKeys[i].Values[0].ToString();
                //log.ItemName = "Devices";
                //log.ItemFullUrl = "DeviceList.aspx";
                //log.CreatedBy = Context.User.Identity.Name;
                //log.CreatedTime = DateTime.Now;
                //log.UserIP = Request.UserHostAddress;
                //EventLog.Insert(log);
                string pp = UserGrid.DataKeys[i].Values[0].ToString();
                //删除附件
                List<AttachmentInfo> AttachmentList = Attachment.GetList("ItemID='" + pp + "'");
                foreach (AttachmentInfo info in AttachmentList)
                {
                    string Attfile = Server.MapPath("../" + info.FilePath);
                    if (File.Exists(Attfile))
                    {
                        FileInfo file = new FileInfo(Attfile);
                        file.IsReadOnly = false;
                        file.Delete();
                    }
                    Attachment.Delete(info.FileID);
                }
                //图片
                Guid id = new Guid(UserGrid.DataKeys[i].Values[0].ToString());
                string fileName = Yipusoft.TownshipEnterprise.BLL.TownDevices.GetTownDevices(id).Picture;
                if (fileName != "")
                {
                    System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath("pics\\") + fileName);
                    if (file.Exists)
                    {
                        file.IsReadOnly = false;
                        file.Delete();
                    }
                }

                Yipusoft.TownshipEnterprise.BLL.TownDevices.Delete(id);

                affectedRows++;

            }
        }
        BindGrid((int)ViewState["PageIndex"]);
        Prompt.Text = "提示：共删除" + affectedRows.ToString() + "条记录！";
    }


    /// <summary>
    /// 绑定GridView
    /// </summary>
    private void BindGrid(int pageIndex)
    {
        ViewState["PageIndex"] = pageIndex;

        string where = "";

        where = Request.QueryString["Where"];
        if (where == null)
            where = "";
        //统计页转来
        if (where != "")
        {
            top.Visible = false;
            UserGrid.Columns[0].Visible = false;
        }
        else
        {

            if (UnitList.SelectedValue != "")
            {
                where += where == "" ? "" : " And ";
                where += " DepartmentID='" + UnitList.SelectedValue + "' ";
            }
            else
            {
                if (DepartmentList.SelectedValue == "")
                {
                    UserInfo userInfo = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
                    DepartmentInfo department = Department.GetDepartment(userInfo.DepartmentID);
                    if (userInfo.DepartmentID.Substring(0, 4) != "1300")
                    {
                        where += where == "" ? "" : " And ";
                        where += " DepartmentID like '" + userInfo.DepartmentID.Substring(0, 4) + "%' ";
                    }
                }
                else
                {
                    where += where == "" ? "" : " And ";
                    where += " DepartmentID like '" + DepartmentList.SelectedValue.Substring(0, 4) + "%' ";
                }
            }


           

            if (DeviceTypeList.SelectedValue != "")
            {
                if (DeviceClassList.SelectedValue == "")
                {
                    where += where == "" ? "" : " And ";
                    where += " deviceclass like '" + DeviceTypeList.SelectedValue.Substring(0, 8) + "__'";
                }
                else
                {
                    where += where == "" ? "" : " And ";
                    CodeItemInfo item = CodeItem.GetCodeItem(DeviceClassList.SelectedValue);

                    if (item.ItemLevel == 0)
                        where += " left(deviceclass,6)='" + DeviceClassList.SelectedValue.Substring(0, 6) + "'";
                    if (item.ItemLevel == 1)
                        where += " left(deviceclass,8)='" + DeviceClassList.SelectedValue.Substring(0, 8) + "'";
                    if (item.ItemLevel == 2)
                        where += " deviceclass='" + DeviceClassList.SelectedValue + "'";

                }
            }
        }
            List<TownDevicesInfo> list = TownDevices.GetList(where, ListPageContral1.PageSize, pageIndex);
            if (list != null)
            {
                this.ListPageContral1.ItemCount = TownDevices.GetCount(where);
                this.UserGrid.DataSource = list;
                this.UserGrid.DataBind();
            }
            //StringBuilder selectCommandText = new StringBuilder();
            //where = where == "" ? where : " where " + where;
            //selectCommandText.Append("select * from Towndevices " + where);
            //selectCommandText.Append(" order by TownBasicID");
            //UserGrid.DataSource = BaseSplitPage.GetPageData(selectCommandText.ToString(), (int)ViewState["PageIndex"], pageSize);
            //UserGrid.DataBind();

            //int totalCount = BaseSplitPage.GetRowCount(selectCommandText.ToString(), (int)ViewState["PageIndex"], pageSize);
            //ViewState["PageCount"] = BaseSplitPage.GetPageCount(selectCommandText.ToString(), (int)ViewState["PageIndex"], pageSize);
            //lbGridInfo.Text = "共有<b>" + totalCount.ToString() + "</b>条记录 第<b>" + ((int)ViewState["PageIndex"] + 1).ToString() + "</b>页 共<b>" + ViewState["PageCount"].ToString() + "</b>页 每页<b>" + pageSize.ToString() + "</b>条";
            //this.btnFirst.Enabled = (int)ViewState["PageIndex"] > 0;
            //this.btnPrev.Enabled = (int)ViewState["PageIndex"] > 0;
            //this.btnNext.Enabled = (int)ViewState["PageIndex"] < (int)ViewState["PageCount"] - 1;
            //this.btnLast.Enabled = (int)ViewState["PageIndex"] < (int)ViewState["PageCount"] - 1;
            //BindJumpList();
        
    }
    protected void UserGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label ID = (Label)e.Row.FindControl("ID");
            ID.Text = (((int)ViewState["PageIndex"]) * pageSize + (e.Row.RowIndex + 1)).ToString();
            //当鼠标放上去的时候 先保存当前行的背景颜色 并给附一颜色 
            e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#F5F5F5',this.style.fontWeight='';");
            //当鼠标离开的时候 将背景颜色还原的以前的颜色 
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor,this.style.fontWeight='';");
        }
    }
    protected void btnFirst_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = 0;
        BindGrid((int)ViewState["PageIndex"]);
    }
    protected void btnPrev_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageIndex"] - 1;
        BindGrid((int)ViewState["PageIndex"]);
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageIndex"] + 1;
        BindGrid((int)ViewState["PageIndex"]);
    }
    protected void btnLast_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageCount"] - 1;
        BindGrid((int)ViewState["PageIndex"]);
    }
    //private void BindJumpList()
    //{
    //    JumpList.Items.Clear();
    //    ListItem li;
    //    for (int i = 0; i < (int)ViewState["PageCount"]; i++)
    //    {
    //        li = new ListItem();
    //        li.Text = (i + 1).ToString();
    //        li.Value = i.ToString();
    //        JumpList.Items.Add(li);
    //    }
    //    JumpList.SelectedIndex = JumpList.Items.IndexOf(JumpList.Items.FindByValue(ViewState["PageIndex"].ToString()));
    //}
    protected void JumpList_SelectedIndexChanged(object sender, EventArgs e)
    {
        //BindGrid(int.Parse(JumpList.SelectedValue));
    }
    #endregion

    protected string GetDepartmentName(string data)
    {
        if (data != "")
        {
            Guid aG = new Guid(data);
            TownBasicInfo tbi = TownBasic.GetTownBasic(aG);
            if (tbi!= null)
                return tbi.Army;
            else
                return "";
        }
        else
        {
            return "";
        }
    }

    void BindType()
    {
        DeviceTypeList.DataTextField = "ItemName";
        DeviceTypeList.DataValueField = "ItemID";
        DeviceTypeList.DataSource = CodeItem.GetList(" parentID='ZBQC010000' order by ItemID,SeqID ");
        DeviceTypeList.DataBind();
    }
    protected void DeviceTypeList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindClass();
        BindGrid(0);
    }

    private void BindClass()
    {
        DeviceClassList.Items.Clear();
        DeviceClassList.Items.Add(new ListItem("--类别--", ""));
        if (DeviceTypeList.SelectedValue != "")
        {
            DeviceClassList.DataTextField = "ItemName";
            DeviceClassList.DataValueField = "ItemID";
            DeviceClassList.DataSource = CodeItem.GetList(" parentID='" + DeviceTypeList.SelectedValue + "' order by ItemID,SeqID ");
            DeviceClassList.DataBind();
        }
        else
        {
            DeviceClassList.DataSource = "";
            DeviceClassList.DataBind();
        }
    }

    public string GetType(string deviceClass)
    {
        Yipusoft.Common.Model.CodeItemInfo info = CodeItem.GetCodeItem(deviceClass);
        if (info != null)
        {
            if (info.ItemLevel == 2)
            {
                return CodeItem.GetCodeItem(info.ParentID).ItemName;
            }
            else
            {
                return info.ItemName;
            }
        }
        else
        {
            return "";
        }
    }

    protected void DepartmentList_TextChanged(object sender, EventArgs e)
    {
        DepartmentListBind();

        BindGrid(0);
    }
    protected void UnitList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindGrid(0);
    }
    protected void ListPageContral1_PageSizeChange(int pageSize, int PageIndex)
    {
        //this.GvwList.PageIndex = PageIndex;
        BindGrid(PageIndex);
    }
}

